﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Windows;
using System.Xml;
using Microsoft.Win32;
using Xliff.Ui.Data;
using Xliff.Ui.Domain;
using Xliff.Ui.Model;

namespace Xliff.Ui.Views
{
    /// <summary>
    /// Interaction logic for MainWindow.xaml
    /// </summary>
    public partial class MainWindow : Window
    {
        private readonly FilterCriteria _criteria = new FilterCriteria();
        private TranslationUnitRepository _translationUnitRepository;

        public MainWindow()
        {
            InitializeComponent();

            tbId.BindWith(_criteria, "Id");
            tbOriginal.BindWith(_criteria, "Original");
            tbTranslated.BindWith(_criteria, "Translated");
            chbShowUntranslated.BindWith(_criteria, "ShowUntranslated");
        }

        public ObservableCollection<TranslationUnit> Translations
        {
            get { return (ObservableCollection<TranslationUnit>) gvTranslations.ItemsSource; }
            set { gvTranslations.ItemsSource = value; }
        }


        private void Show(IEnumerable<TranslationUnit> translations)
        {
            Translations = new ObservableCollection<TranslationUnit>(translations);
        }

        private void btnFilter_Click(object sender, RoutedEventArgs e)
        {
            IEnumerable<TranslationUnit> translations = _translationUnitRepository.GetByCriteria(_criteria);
            Show(translations);
        }

        private void btnOpen_Click(object sender, RoutedEventArgs e)
        {
            var ofd = new OpenFileDialog {Filter = "Data Sources (*.xlf, *.xml)|*.xlf*;*.xml|All Files|*.*"};

            if (ofd.ShowDialog() != true)
                return;

            _translationUnitRepository = new TranslationUnitRepository(ofd.FileName);

            try
            {
                IList<TranslationUnit> translations = _translationUnitRepository.GetAll();
                Show(translations);
            }
            catch (XmlException)
            {
                MessageBox.Show(this, "Input file is not a valid .xlf file.", "Error", MessageBoxButton.OK, MessageBoxImage.Error);
            }
        }

        private void btnSave_Click(object sender, RoutedEventArgs e)
        {
            _translationUnitRepository.SaveChanges(Translations);
        }
    }
}